import { http } from './http'

const host = "https://gitee.com/api/v5";
// 仓库作者
const owner = "getActivity"
// 仓库名
const repo = "EmojiPackage"

class giteeHttp {
  constructor() {
    this.token = "4b8a95e3383aaaadff74399c3fb951b2";
  }


  /**
   * api
   * GET https://gitee.com/api/v5/repos/{owner}/{repo}/contents(/{path})
   * 
   * eg:
   * https://gitee.com/api/v5/repos/getActivity/EmojiPackage/contents/%2F?access_token=a09134059faffae87c53f3ad88d1ee26
   */
  getRepoContents(path) {
    console.log("getRepoContents")
    return new Promise((resolve, reject) => {
      let url = host + "/repos/" + owner + "/" + repo + "/contents/" + path + "?access_token=" + this.token;
      http(url, { method: "get" }).then(res => {
        this.getSecondContents(res).then(resolve).catch(reject);
      }).catch(reject);
    })
  }

  /**
   * 获取第二层级的内容
   * 因为这个库里就两层，所以就不搞递归了（狗头）
   * @param {第一层级返回的数据} res 
   */
  getSecondContents(res) {
    console.log("getSecondContents")
    return new Promise((resolve) => {
      if (!res || res.length == 0) {
        resolve(res);
        return;
      }
      var promiseArray = new Array(1);
      for (let index = 0; index < 1; index++) {
        promiseArray[index] = this.getOneDictonaryContents(res[index])
      }
      Promise.all(promiseArray).then(() => {
        resolve(res)
      }).catch(err => {
        console.err(err);
        resolve(res)
      })
    })
  }

  getOneDictonaryContents(item) {
    return new Promise((resolve, reject) => {
      // item.label = item.name;
      let url = host + "/repos/" + owner + "/" + repo + "/contents/" + item.path + "?access_token=" + this.token;
      http(url, { method: "get" }).then(res => {
        item.children = res;
        if (res) {
          // res.forEach(childItem => {
          //   childItem.label = childItem.name;
          // })
        }
        resolve()
      }).catch(reject);
    })
  }
}
export default new giteeHttp();